<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web Components Example</title>
</head>
<body>
<my-custom-element></my-custom-element>

<script>
    // 定义自定义元素类
    class MyCustomElement extends HTMLElement {
        constructor() {
            super();
            // 创建 Shadow DOM
            const shadowRoot = this.attachShadow({ mode: 'open' });
            // 创建元素内容
            const wrapper = document.createElement('div');
            wrapper.innerHTML = `
              <style>
                h1 {
                  color: blue;
                }
                p {
                  font-size: 16px;
                  color: green;
                }
              </style>
              <h1>Hello, Web Components!</h1>
              <p>This is a custom element.</p>
            `;

            // 将内容附加到 Shadow DOM
            shadowRoot.appendChild(wrapper);
        }

        // 连接生命周期回调
        connectedCallback() {
            console.log('MyCustomElement has been added to the DOM.');
        }
        disconnectedCallback() {
            console.log('MyCustomElement has been removed from the DOM.');
        }
        adoptedCallback() {
            console.log('MyCustomElement has been moved to a new document.');
        }
        attributeChangedCallback(name, oldValue, newValue) {
            console.log(`Attribute ${name} changed from ${oldValue} to ${newValue}`);
        }

        static get observedAttributes() {
            return ['custom-attribute'];
        }
    }

    // 注册自定义元素
    customElements.define('my-custom-element', MyCustomElement);
</script>
</body>
</html>